package com.tycmc.signelectroniccontracts.tools.other;

import android.text.InputFilter;
import android.text.Spanned;

/**
 * Created by gaoyong on 2018/3/19.
 * 限制字符的长度 1个汉字等于2个字符
 */

public class NameLengthFilter implements InputFilter {
    int MAX_EN;

    public NameLengthFilter(int mAX_EN) {
        super();
        MAX_EN = mAX_EN;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end,
                               Spanned dest, int dstart, int dend) {
        int destCount =  TextShow.getChineseCount(dest.toString());
        int sourceCount =  TextShow.getChineseCount(source.toString());
        if (destCount + sourceCount > MAX_EN) {
            int surplusCount = MAX_EN - destCount;
            String result = "";
            int index = 0;
            while (surplusCount > 0) {
                char c = source.charAt(index);
                if (TextShow.isChineseByBlock(c )||TextShow.isChinesePunctuation(c)) {
                    if (surplusCount >= 2) {
                        result += c;
                    }
                    surplusCount = surplusCount - 2;
                } else {
                    result += c;
                    surplusCount = surplusCount - 1;
                }
                index++;
            }
            return result;
        } else {
            return source;
        }
    }


}
